package com.auxgroup.smarthome.event;


import com.alibaba.fastjson.JSONObject;
import com.auxgroup.smarthome.constant.cache.CachedConsant;
import com.auxgroup.smarthome.entity.AppFilterFaultEntity;
import com.auxgroup.smarthome.entity.DeviceInfoEntity;
import com.auxgroup.smarthome.redis.config.ObjectRedis;
import com.auxgroup.smarthome.repo.AppFilterFaultRepo;
import com.auxgroup.smarthome.repo.DeviceInfoEntityRepo;
import com.auxgroup.smarthome.service.AppControlFuncService;
import com.auxgroup.smarthome.snoti.events.IPushEvent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.Date;

/**
 *  下线以及时间同步
 * 下线事件
 * @Author: laiqiuhua.
 * @Date: 2017/9/4 15:42.
 */
@Component
public class OfflineEvent implements IPushEvent {
    @Autowired
    private DeviceInfoEntityRepo deviceInfoEntityRepo;

    @Autowired
    private AppFilterFaultRepo appFilterFaultRepo;

    @Autowired
    private AppControlFuncService appControlFuncService;

    @Autowired
    private ObjectRedis objectRedis;

    private final String pathKey = CachedConsant.DEVICE_FILTER_FAULT_PREFIX;

    @Override
    public void callback(String message) {
        JSONObject msg = JSONObject.parseObject(message);
        String productKey = msg.getString("product_key");
        String mac = msg.getString("mac").toUpperCase();
        String did = msg.getString("did");
        DeviceInfoEntity deviceInfoEntity = deviceInfoEntityRepo.findByMacAndTrashFalse(mac);
        if(null != deviceInfoEntity) {
            deviceInfoEntity.setOnline(false);
            deviceInfoEntity.setDid(did);
            deviceInfoEntityRepo.save(deviceInfoEntity);
        }
        calculateTime(mac);
    }


    /**
     * 关机状态下 清空缓存并且持久化数据 滤网清洗
     * @param mac
     */
    public void calculateTime(String mac){
        String key = pathKey+mac;
        Long onTime = objectRedis.get(key,Long.class);
        double d = (double) (new Date().getTime() - onTime)/60000;
        int evl = new BigDecimal(d).setScale(0, BigDecimal.ROUND_HALF_UP).intValue();
        AppFilterFaultEntity appFilterFaultEntity = appFilterFaultRepo.findByMac(mac);
        if(null != appFilterFaultEntity) {
            if(!appFilterFaultEntity.getWash() && (appFilterFaultEntity.getBootTime()+evl) > 500*60){
                appFilterFaultEntity.setWash(true);
            }
            appFilterFaultEntity.setBootTime(appFilterFaultEntity.getBootTime()+evl);
            appFilterFaultRepo.save(appFilterFaultEntity);
            objectRedis.delete(key);
        }else{
            appFilterFaultEntity = new AppFilterFaultEntity(mac,evl,false);
            appFilterFaultRepo.save(appFilterFaultEntity);
        }
    }
}
